package com.htdata.iiot.UpdateMqttPass;

import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

import org.apache.commons.codec.digest.DigestUtils;

public class PasswordHash {
	public static final int SALT_BYTE_SIZE = 24;
	private static final int HASH_BYTE_SIZE = 24;
	public static final int PBKDF2_ITERATIONS = 1000;
	public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";
	
	
	private static byte[] fromHex(String hex) {
		byte[] binary = new byte[hex.length() / 2];
		for (int i = 0; i < binary.length; i++) {
			binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
		}
		return binary;
	}

	private static String toHex(byte[] array) {
		BigInteger bi = new BigInteger(1, array);
		String hex = bi.toString(16);
		int paddingLength = (array.length * 2) - hex.length();
		if (paddingLength > 0)
			return String.format("%0" + paddingLength + "d", 0) + hex;
		else
			return hex;
	}

	private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes)
			throws NoSuchAlgorithmException, InvalidKeySpecException {
		PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
		SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
		return skf.generateSecret(spec).getEncoded();
	}

	public static String createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException {
		String sha1Pass = DigestUtils.shaHex(password);
		// Hash the password
		byte[] hash = pbkdf2(sha1Pass.toCharArray(), fromHex(sha1Pass), PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
		// format iterations:salt:hash
		String test = PBKDF2_ITERATIONS + ":" + sha1Pass + ":" + toHex(hash);
		return PBKDF2_ITERATIONS + ":" + sha1Pass + ":" + toHex(hash);
	}

	public static boolean validatePassword(String password, String sult, int iterations, String pbk)
			throws NoSuchAlgorithmException, InvalidKeySpecException {
		// Compute the hash of the provided password, using the same salt,
		// iteration count, and hash length

		byte[] testHash = pbkdf2(DigestUtils.shaHex(password).toCharArray(), fromHex(sult), iterations, HASH_BYTE_SIZE);
		// Compare the hashes in constant time. The password is correct if
		// both hashes match.
		return toHex(testHash).equals(pbk);
	}
}
